package com.droidblackbox;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.droidblackbox.accident.Accident;
import com.droidblackbox.history.History;
import com.droidblackbox.info.SystemInfo;
import com.droidblackbox.log.Log;
import com.droidblackbox.manager.C2DMManager;
import com.droidblackbox.manager.DisplayManager;
import com.droidblackbox.manager.FileManager;
import com.droidblackbox.manager.SystemManager;
import com.droidblackbox.manager.WASManager;
import com.droidblackbox.memory.MemoryStatus;
import com.droidblackbox.preference.PreferManager;
import com.droidblackbox.preference.Preference;
import com.droidblackbox.receiver.GPSStateReceiver;
import com.droidblackbox.receiver.InternetStateReceiver;
import com.droidblackbox.record.RecordView;

public class DroidBlackBox extends Activity implements OnClickListener,
		Handler.Callback {
	private static final int ID_MENU_LAYOUT_0 = 0x00000001;
	private static final int ID_MENU_LAYOUT_1 = 0x00000010;
	private static final int ID_MENU_LAYOUT_2 = 0x00000100;
	private static final int ID_MENU_LAYOUT_3 = 0x00001000;
	private static final int ID_MENU_LAYOUT_4 = 0x00010000;
	private static final int ID_MENU_LAYOUT_5 = 0x00100000;

	private static final int STATE_MESSAGE = 0x11110000;
	private static final int REGISTRATION = 0x10010100;

	private TextView mainInfoText = null;
	private Handler handler = null;
	private Intent intent = null;

	private GPSStateReceiver gpsStateReceiver = null;
	private InternetStateReceiver internetStateReceiver = null;

	private boolean isLoop = true;

	private String[] weeks = null;

	private int orientation = Configuration.ORIENTATION_PORTRAIT;

	private static final int DIALOG_PROGRESS = 1;
	private static final int MAX_PROGRESS = 30;
	private ProgressDialog progressDialog = null;

	private AddAsyncTask addAsyncTask = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Resources r = Resources.getSystem();
		Configuration config = r.getConfiguration();
		orientation = config.orientation;
		onStartApp();

		addAsyncTask = new AddAsyncTask();
		addAsyncTask.execute();

	}

	class AddAsyncTask extends AsyncTask<Void, Integer, Void> {

		@Override
		protected void onPreExecute() {
			try {

				showDialog(DIALOG_PROGRESS);
				progressDialog.setProgress(0);

			} catch (Exception e) {
			}

		}

		@Override
		protected Void doInBackground(Void... unused) {

			for (int i = 0; i < MAX_PROGRESS; i++) {
				publishProgress(i);
				SystemClock.sleep(10);
			}
			return (null);
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			progressDialog.setProgress(progress[0]);
		}

		@Override
		protected void onPostExecute(Void unused) {
			progressDialog.dismiss();
			dismissDialog(DIALOG_PROGRESS);
		}

		protected void onCancelled() {
			progressDialog.dismiss();
			dismissDialog(DIALOG_PROGRESS);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		isLoop = true;
		Thread thread = new Thread(new Runnable() {

			public void run() {
				handler.sendEmptyMessage(REGISTRATION);
				while (isLoop) {
					try {
						handler.sendEmptyMessage(STATE_MESSAGE);
						Thread.sleep(1500);

						if (progressDialog.isShowing()) {
							progressDialog.dismiss();
						}
					} catch (Exception e) {
					}
				}
			}
		});
		thread.setName("State Message");
		thread.setDaemon(true);
		thread.start();

	}

	@Override
	protected void onPause() {
		super.onPause();
		isLoop = false;

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		addAsyncTask.cancel(true);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		switch (newConfig.orientation) {
		case Configuration.ORIENTATION_PORTRAIT:
			orientation = Configuration.ORIENTATION_PORTRAIT;
			break;
		case Configuration.ORIENTATION_LANDSCAPE:
			orientation = Configuration.ORIENTATION_LANDSCAPE;
			break;
		}
		setContentView(R.layout.main);
		onStartApp();

		new AddAsyncTask().execute();

	}

	@Override
	public Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_PROGRESS:

			progressDialog = new ProgressDialog(DroidBlackBox.this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressDialog.setTitle("DrodiBlackBox");
			progressDialog.setMessage("Loading..... Please wait..");
			progressDialog.setCancelable(false);
			progressDialog.setMax(MAX_PROGRESS); // Max값 100
			return progressDialog;

		}
		return null;
	}

	private void onStartApp() {
		try {
			initComponent();
			initReceiver();
			initApplication();
		} catch (IOException e) {
			final String string = getResources().getString(
					R.string.error_io_exception);
			Toast.makeText(this, string, Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void initComponent() throws Exception {
		weeks = getResources().getStringArray(R.array.weeks);

		mainInfoText = (TextView) findViewById(R.id.mainInfoText);
		mainInfoText.setTag("");
		mainInfoText.setTextSize(getResources().getDimension(
				R.dimen.main_text_size));
		mainInfoText.setTextColor(getResources().getColor(
				R.color.main_text_color));

		String pkg = getPackageName();
		for (int i = 0; i < 6; i++) {
			int id = getResources().getIdentifier("menuLayout" + i, "id", pkg);
			double d = Math.pow(16, i);

			LinearLayout layout = (LinearLayout) findViewById(id);
			layout.setId((int) d);
			layout.setOnClickListener(this);
		}

	}

	private void initApplication() throws IOException {
		handler = new Handler(this);

		FileManager.setInstance(this).onInit();
		DisplayManager.setInstance(this);
		PreferManager.setInstance(this);
		C2DMManager.getInstance();

		final String serverAddress = PreferManager
				.get(PreferManager.KEY_STRING_SERVER_ADDRESS);
		WASManager.getInstance();
		WASManager.getInstance().setHost(serverAddress);
		WASManager.getInstance().setPort(8080);
		WASManager.getInstance().setPage("index.jsp");
	}

	private void initReceiver() throws Exception {
		gpsStateReceiver = new GPSStateReceiver();
		IntentFilter gpsFilter = new IntentFilter();
		gpsFilter.addAction("android.location.PROVIDERS_CHANGED");
		registerReceiver(gpsStateReceiver, gpsFilter);

		internetStateReceiver = new InternetStateReceiver();
		IntentFilter internetFilter = new IntentFilter();
		gpsFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
		registerReceiver(internetStateReceiver, internetFilter);

	}

	private void unReceiver() throws Exception {
		unregisterReceiver(gpsStateReceiver);
		unregisterReceiver(internetStateReceiver);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case ID_MENU_LAYOUT_0:
			intent = null;
			intent = new Intent(this, RecordView.class);
			break;
		case ID_MENU_LAYOUT_1:
			intent = null;
			intent = new Intent(this, History.class);
			break;
		case ID_MENU_LAYOUT_2:
			intent = null;
			intent = new Intent(this, Log.class);
			break;
		case ID_MENU_LAYOUT_3:
			intent = null;
			intent = new Intent(this, Accident.class);
			break;
		case ID_MENU_LAYOUT_4:
			intent = null;
			intent = new Intent(this, MemoryStatus.class);
			break;
		case ID_MENU_LAYOUT_5:
			intent = null;
			intent = new Intent(this, Preference.class);
			break;
		}

		final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
				intent, PendingIntent.FLAG_ONE_SHOT);
		try {
			pendingIntent.send();
		} catch (CanceledException e) {
			e.printStackTrace();
		}

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (keyCode) {
			case KeyEvent.KEYCODE_CAMERA:
				try {

					Map<String, String> message = new HashMap<String, String>();
					String myNumber = C2DMManager.getInstance().getNumber();
					message.put(C2DMManager.KEY_PUSH_NUMBER, myNumber);
					message.put(C2DMManager.KEY_PUSH_SUBMESSAGE, getResources()
							.getString(R.string.receive_message));
					message.put(C2DMManager.KEY_PUSH_1, "msg1");
					message.put(C2DMManager.KEY_PUSH_2, "msg2");
					message.put(C2DMManager.KEY_PUSH_3, "msg3");
					message.put(C2DMManager.KEY_PUSH_4, "msg4");
					message.put(C2DMManager.KEY_PUSH_5, "msg5");

				//	C2DMManager.push("+821033708753", message);
					File file = new File("/mnt/sdcard/◎_image_1.jpg");
					FileInputStream fis = new FileInputStream(file);
					System.out.println(file.getName());
					WASManager.conn(fis, file.getName());
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			case KeyEvent.KEYCODE_BACK:
				appExit();
				return true;
			}
		}
		return false;
	}

	private void appExit() {
		try {
			unReceiver();
		} catch (Exception e) {
		}

		moveTaskToBack(true);
		finish();
		System.exit(0);
	}

	public String getMessage() {
		String string = "";

		switch (orientation) {
		case Configuration.ORIENTATION_PORTRAIT:
			string = getPortMessage();
			break;
		case Configuration.ORIENTATION_LANDSCAPE:
			string = getLandMessage();
			break;
		}

		return string;
	}

	private String getLandMessage() {
		StringBuffer sb = new StringBuffer();
		Calendar calendar = Calendar.getInstance();
		String s1 = getResources().getString(R.string.main_internet_on);
		String s2 = getResources().getString(R.string.main_internet_off);
		String s3 = getResources().getString(R.string.main_gps_on);
		String s4 = getResources().getString(R.string.main_gps_off);
		sb.append(calendar.get(Calendar.YEAR));
		sb.append(" . ");
		sb.append(calendar.get(Calendar.MONTH) + 1);
		sb.append(" . ");
		sb.append(calendar.get(Calendar.DAY_OF_MONTH));
		sb.append(" . ");
		sb.append(" ( ");
		sb.append(weeks[calendar.get(Calendar.DAY_OF_WEEK) - 1]);
		sb.append(" ) ");
		sb.append("  /  ");

		if (SystemManager.getInstance().isInternet(this))
			sb.append(s1);
		else
			sb.append(s2);

		sb.append("  /  ");

		if (SystemManager.getInstance().isGps(this))
			sb.append(s3);
		else
			sb.append(s4);
		return sb.toString();
	}

	private String getPortMessage() {
		StringBuffer sb = new StringBuffer();
		Calendar calendar = Calendar.getInstance();
		String s1 = getResources().getString(R.string.main_internet_on);
		String s2 = getResources().getString(R.string.main_internet_off);
		String s3 = getResources().getString(R.string.main_gps_on);
		String s4 = getResources().getString(R.string.main_gps_off);
		sb.append(calendar.get(Calendar.YEAR));
		sb.append(" . ");
		sb.append(calendar.get(Calendar.MONTH) + 1);
		sb.append(" . ");
		sb.append(calendar.get(Calendar.DAY_OF_MONTH));
		sb.append(" . ");
		sb.append(" ( ");
		sb.append(weeks[calendar.get(Calendar.DAY_OF_WEEK) - 1]);
		sb.append(" ) ");
		sb.append("\r\n");

		if (SystemManager.getInstance().isInternet(this))
			sb.append(s1);
		else
			sb.append(s2);

		sb.append("\r\n");

		if (SystemManager.getInstance().isGps(this))
			sb.append(s3);
		else
			sb.append(s4);

		return sb.toString();
	}

	private void setRegistration() {
		SystemInfo info = FileManager.getSystemInfo(this);

		if (info.getRegistration() == null) {
			Intent registrationIntent = new Intent(C2DMManager.INTENT_REGISTER);
			registrationIntent.putExtra("app", PendingIntent.getBroadcast(this,
					0, new Intent(), PendingIntent.FLAG_ONE_SHOT));
			registrationIntent.putExtra("sender", WASManager.EMAIL);
			startService(registrationIntent);
		} else {
			C2DMManager.getInstance().setRegistration(info.getRegistration());
			C2DMManager.getInstance().setNumber(info.getNumber());
		}
	}

	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case STATE_MESSAGE:
			mainInfoText.setText(getMessage());
			break;
		case REGISTRATION:
			setRegistration();
			break;
		}
		return true;
	}
}
